/*
 **modification:2016-11-2
 **author:easterCat
 **version:1.0.0
 */

;
(function($, window, document) {
    //设置一个闭包对象
    var TreeMenu = (function() {
        function TreeMenu(element, options) {
            this.settings = $.extend(true, $.fn.TreeMenu.defaults, options || {});
            this.element = element;
            this.init();
        }
        TreeMenu.prototype = {
            //初始化插件
            init: function() {
                //console.log(this); //TreeMenu指的是TreeMenu对象，带有属性方法
                //console.log(this.element); //ul#myTree指的是元素
                var me = this;
                me.showTreeTable(me.settings.showTree, me.settings.togglerDelay);
                me.analysis(me.settings.putJSON); //调用解析json的函数
                me.element.addClass(me.settings.chooseStyle);
                me._initButtonClick();
                me.onlyOneOpen(me.settings.onlyUnfold);
            },
            //设置基本的打开关闭效果
            _initButtonClick: function() {
                var me = this;
                var settings = this.settings;
                me.element.find("li").each(function() {
                    e = $(this); //此处的e是tree的第一级li
                    var subtree = e.find('> ul');
                    var button = e.find('span').eq(0).addClass('toggler');
                    if (button.length == 0) {
                        var button = $('<span>');
                        button.addClass('toggler');
                        //在e的开头添加元素span
                        e.prepend(button); //默认的自写添加span方法，无法读取json
                    } else {
                        button.addClass('toggler');
                    }
                    //当传入的值是false时,则列表默认为关闭状态
                    if (subtree.length > 0 && settings.listState == false) {
                        //此处控制默认2级以上列表是展开还是关闭
                        subtree.hide();
                        e.addClass('tree-closed');
                        e.find(button).click(function() {
                            var li = $(this).parent('li');
                            li.find('> ul').slideToggle(me.settings.delay);
                            li.toggleClass('tree-opened');
                            li.toggleClass('tree-closed');
                            //某一级别的ul的子元素不存在，则兄弟span点击事件取消，鼠标移上的效果消失，无法打开
                            $("#myTree ul").each(function(index) {
                                if ($("#myTree ul").eq(index).children("li").length == 0) {
                                    $("#myTree ul").eq(index).siblings("span.toggler").css("cursor", "default").unbind("click");
                                }
                            })
                        })
                    } else {
                        $(this).addClass('tree-empty');
                    };

                    //当传入的值是true时，则列表默认为打开状态
                    if (subtree.length > 0 && settings.listState == true) {
                        subtree.show();
                        e.addClass('tree-opened');
                        e.find(button).click(function() {
                            var li = $(this).parent('li');
                            li.find('> ul').slideToggle(me.settings.delay);
                            li.toggleClass('tree-opened');
                            li.toggleClass('tree-closed');

                            //某一级别的ul的子元素不存在，则兄弟span点击事件取消，鼠标移上的效果消失，无法打开
                            $("#myTree ul").each(function(index) {
                                if ($("#myTree ul").eq(index).children("li").length == 0) {
                                    $("#myTree ul").eq(index).siblings("span.toggler").css("cursor", "default").unbind("click");
                                }
                            });
                            //当某一级别ul关闭的时候，他子元素的ul也要同时处于关闭状态
                            $("#myTree ul").each(function(index) {
                                if ($("#myTree ul").eq(index).css("display") == 'none') {
                                    console.log(index);
                                }
                            })
                        });
                    } else {
                        $(this).addClass('tree-empty');
                    };
                });
                me.showCheckBox(me.settings.showCheckbox);
            },
            //解析json语句生成html语句
            analysis: function(data) {
                var me = this;
                console.log(data.length);
                for (var i = 0; i < data.length; i++) {
                    var data2 = data[i];
                    if (data[i].level == "1") { //初次采用长度判断，最多生成9个列
                        $("#myTree").append("<li data-name='" + data[i].code + "'><span class='span_level'></span> <a href='#'>" + data[i].name + "</a></li>");
                    } else {
                        var children = $("li[data-name='" + data[i].parentCode + "']").children('ul');
                        if (children.length == 0) {
                            $("li[data-name='" + data[i].parentCode + "']").append("<ul></ul>")
                        }
                        $("li[data-name='" + data[i].parentCode + "']>ul").append(
                            "<li data-name='" + data[i].code + "'><span class='span_level'></span><a href='#'>" + data[i].name + "</a><ul></ul></li>"
                        )
                    }
                    for (var j = 0; j < data[i].child.length; j++) {
                        var child = data[i].child[j];
                        var children = $("li[data-name='" + child.parentCode + "']").children('ul');
                        if (children.length == 0) {
                            $("li[data-name='" + child.parentCode + "']").append("<ul></ul>");
                        }
                        $("li[data-name='" + child.parentCode + "'] > ul").append(
                            "<li data-name='" + child.code + "'><span class='span_level'></span><a href='#'>" + child.name + "</a><ul></ul></li>")
                        var child2 = data[i].child[j].child;
                        me.analysis(child2);
                    }
                    me.analysis(data[i]);
                }
            },
            //点击input判断是否够生成下拉树表
            showTreeTable: function(status, showspeed) {
                var me = this;
                if (status == false) {
                    $("#myTree").hide();
                    var open = true;
                    $(".inputTree").click(function() {

                        if (open === true) {
                            //获取input的当前的offset值，当tree出现时候，定位到input下面
                            var inputDisTop = $(".inputTree").offset().top;
                            var inputDisLeft = $(".inputTree").offset().left;
                            //console.log(inputDis); //返回一个offset对象，带有top和left两个属性
                            var inputH = $(".inputTree").height();
                            //console.log(inputDis.top); //返回top属性
                            //console.log(inputDis.left); //返回left属性
                            //console.log(inputH); //返回input高度
                            var $top = inputDisTop + inputH;
                            var $left = inputDisLeft;
                            $("#myTree").offset({ top: $top, left: $left });
                            $("#myTree").width($(".inputTree").width());
                            $("#myTree").slideDown(showspeed);
                            open = false;
                            return open;
                        } else if (open === false) {
                            $("#myTree").slideUp(showspeed);
                            clearInterval(timer);
                            var timer = setTimeout(function() {
                                $("#myTree").css({ top: '0px', left: '0px' });
                            }, showspeed);
                            open = true;
                            return open;
                        }
                    });
                } else {
                    $("#myTree").show();
                }
            },
            //判断是否显示出现选择框
            showCheckBox: function(status) {
                var me = this;
                if (status == false) {
                    $("input[type='checkbox']").hide();
                } else {
                    $("span.span_level").after("<input type='checkbox'>");
                    $("input[type='checkbox']").show();
                }
            },
            /*判断是否打开一开多关的效果*/
            onlyOneOpen: function(status) {
                var me = this;
                if (status == true) {
                    $("#myTree>li>span.span_level").click(function() {
                        var parentLi = $(this).parents('li'); //当前点击span的父对象li
                        // console.log($(this)); //是jquery选择器对象
                        // console.log(this); //是原本的dom对象
                        if (parentLi.is(".tree-opened")) {
                            parentLi.removeClass("tree-closed");
                            parentLi.siblings('li').removeClass('tree-opened');
                            parentLi.siblings('li').find('>ul').slideUp(200);
                            parentLi.siblings('li').addClass("tree-closed");
                        }
                    })
                } else {
                    return false;
                }
            }
        };
        return TreeMenu;
    })();

    //对象级别的开发方式
    $.fn.TreeMenu = function(options) {
        return this.each(function() {
            var $me = $(this),
                instance = $me.data("TreeMenu");
            if (!instance) {
                $me.data("TreeMenu", (instance = new TreeMenu($me, options)));
            }
            if ($.type(options) === "string") return instance[options]();
        })
    };

    //带有默认参数的写法
    $.fn.TreeMenu.defaults = {
        putJSON: [],
        showTree: true, //选择是否显示tree,默认打开
        showCheckbox: false, //选择是否出现选择框，不出现
        chooseStyle: '', //选择主题样式，默认为treemenu
        togglerDelay: '100', //子列表隐藏显示的速度，默认100
        listState: false, //当前所有的子列表是否展开，关闭状态
        onlyUnfold: false //是否打开一开多关的效果,默认关闭
    };
})(jQuery, window, document);
